//
//  BCHomepageSearchTableViewController.m
//  BCVersion
//
//  Created by 吴 崧 on 14-2-23.
//  Copyright (c) 2014年 Jungle. All rights reserved.
//

#import "BCHomepageSearchTableViewController.h"
#import "ClientCell.h"
#import "MJRefreshFooterView.h"
#import "MJRefreshHeaderView.h"
#import "BCManagerInfoViewController.h"
#import "ManagerSearchedModel.h"
#define Search_Table_Height 100
#define Bank_Tag 5
#define Credit_Card_Tag 6
#define Sort_Tag 7


@interface BCHomepageSearchTableViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)NSString *bank;
@property(nonatomic,strong)NSString *work;
@property(nonatomic,strong)NSString *sort;
@property(nonatomic,strong)NSString *city;
@property(nonatomic,strong)NSArray *bankArray;
@property(nonatomic,strong)NSArray *workArray;
@property(nonatomic,strong)NSArray *sortArray;
@property(nonatomic,strong)MJRefreshHeaderView *header;
@property(nonatomic,strong)MJRefreshFooterView *footer;
@property(nonatomic,strong)NSArray *searchConditionArray;
@property (weak, nonatomic) IBOutlet UIButton *bankBtn;
@property (weak, nonatomic) IBOutlet UIButton *sortBtn;
@property(nonatomic,strong)NSArray *cityArray;
@property (weak, nonatomic) IBOutlet UIButton *workBtn;
@property (weak, nonatomic) IBOutlet UIButton *cityBtn;

@property(nonatomic,assign) NSInteger selected_tag;

@end

@implementation BCHomepageSearchTableViewController

-(instancetype)initWithDataSource:(NSArray *)dataSource
                       WorkSource:(NSArray *)workArray
                       BankSource:(NSArray *)bankArray
                       CellHeight:(CGFloat)cellHeight
                     FooterHeight:(CGFloat)footerHeight
                     HeaderHeight:(CGFloat)headerHeight
                          KeyWord:(NSString *)keyWord;
{
    self = [super initWithNibName:@"BCHomepageSearchTableViewController" bundle:nil];
    if (self) {
        self.dataSource = dataSource;
        self.bankArray = bankArray;
        self.workArray = workArray;
        self.defaultCellHeight = cellHeight;
        self.defaultFooterHeight = footerHeight;
        self.defaultHeaderHeight = headerHeight;
        self.keyWord = keyWord;
        self.nextStart = dataSource.count;
        self.limit = SearchLimit;
        self.searchConditionArray = [NSArray array];
        self.sortArray = @[@[@"评分",@"score"],@[@"时间",@"time"],@[@"推荐",@"recommend"]];
        self.cityArray =  @[@[@"北京",@"beijing"],@[@"上海",@"shanghai"],@[@"广州",@"guangzhou"],@[@"深圳",@"shenzhen"]];
        self.sort = @"score";
        self.work = EMPTY_STRING;
        self.bank = EMPTY_STRING;
        self.selectCellNeedLogin = YES;
        self.city = @"beijing";
        _selected_tag = 0;
    
    }
    return self;
}






- (void)viewDidLoad
{
    [super viewDidLoad];
    [self creatEgoFresh];
    self.conditionTable.dataSource = self;
    self.conditionTable.delegate = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self setHidesBottomBarWhenPushed:NO];
}




-(void)creatEgoFresh
{
      __weak typeof(self) weaSelf = self;
    
    MJRefreshFooterView *footer = [MJRefreshFooterView footer];
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
   __weak typeof(header)weakHeader = header;
    __weak typeof(footer)weakFooter = footer;
    
    footer.scrollView = self.tableView;
    
    footer.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        [weaSelf doneReFreshWithView:weakHeader
                          WithSucess:NO];
        [BCNetworkClient searchWithKey:self.keyWord
                                  auth:USER_MANAGER.auth
                                  city:self.city
                                  work:self.work
                                  bank:self.bank
                                 order:self.sort
                                  desc:@"1"
                                 start:self.nextStart
                                 limit:SearchLimit
                               success:^(NSArray *results) {
                                   weaSelf.dataSource = [weaSelf.dataSource arrayByAddingObjectsFromArray: [ManagerSearchedModel modelsWithDataSource:results]] ;
                                   weaSelf.nextStart = weaSelf.dataSource.count;
                                   [weaSelf doneReFreshWithView:refreshView
                                                     WithSucess:YES];
                               }
                               failure:^(NSError *error) {
                                   [weaSelf doneReFreshWithView:refreshView WithSucess:NO];
                               }];
    };
    
 
    
     header.scrollView = self.tableView;
    header.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        [weaSelf doneReFreshWithView:weakFooter
                          WithSucess:NO];
            [BCNetworkClient searchWithKey:self.keyWord
                                      auth:USER_MANAGER.auth
                                      city:self.city
                                      work:self.work
                                      bank:self.bank
                                     order:@"score"
                                      desc:@"1"
                                     start:0
                                     limit:SearchLimit
                                   success:^(NSArray *results) {
                                       weaSelf.dataSource = [ManagerSearchedModel modelsWithDataSource:results];
                                       weaSelf.nextStart = weaSelf.dataSource.count;
                                       [weaSelf doneReFreshWithView:refreshView
                                                         WithSucess:YES];
                                   }
                                   failure:^(NSError *error) {
                                       [weaSelf doneReFreshWithView:refreshView WithSucess:NO];

                                   }];
    };
    header.endStateChangeBlock = ^(MJRefreshBaseView *refreshView) {
        // 刷新完毕就会回调这个Block
        NSLog(@"%@----刷新完毕", refreshView.class);
    };
    
    

}


- (void)doneReFreshWithView:(MJRefreshBaseView *)refreshView
                 WithSucess:(BOOL)sucess;
{
    // 刷新表格
    if (sucess) {
        [self.tableView reloadData];
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        
    }
    [refreshView endRefreshing];
    [refreshView endRefreshingWithoutIdle];
}


- (IBAction)back:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    static NSString *searchCellIdentifier = @"SearchCell";
    BOOL mainTable = [tableView isEqual:self.tableView];
    
    UITableViewCell *cell = mainTable == YES?[tableView dequeueReusableCellWithIdentifier:CellIdentifier]:[tableView dequeueReusableCellWithIdentifier:searchCellIdentifier];
    
    ManagerSearchedModel *model =  mainTable == YES?[self.dataSource objectAtIndex:indexPath.row]:[self.searchConditionArray objectAtIndex:indexPath.row];

    if (cell == nil) {
        cell = mainTable?[self createCellWithReuseIndentifier:CellIdentifier]:[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:searchCellIdentifier];
    }
    // Configure the cell...
    [self tableView:tableView configCell:cell forClient:model atIndexPath:indexPath];
    return cell;
    
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
{
    if ([tableView isEqual:self.tableView]) {
        return self.dataSource.count;
    }else
    {
        return self.searchConditionArray.count;
    }
}


-(UITableViewCell *)createCellWithReuseIndentifier:(NSString *)reuseIdentifier
{
    UITableViewCell *cell = [self loadCellFromNib:@"ClientCell"];
    return cell;
}

- (void)tableView:(UITableView *)tableView configCell:(UITableViewCell *)cell forClient:(NSObject *)client atIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:self.tableView]) {
        __weak ClientCell *clientCell = (ClientCell *)cell;
        [clientCell configWithModel:(ManagerSearchedModel *)client KeyWord:self.keyWord];
    }
    else
    {
        cell.textLabel.font = [UIFont systemFontOfSize:11];
        if ([self.searchConditionArray isEqual:self.sortArray]||[self.searchConditionArray isEqual:self.cityArray]) {
            cell.textLabel.text = [(NSArray *)client objectAtIndex:0];
           
        }else
        {
            cell.textLabel.text = (NSString *)[client valueForKey:@"name"];
        }
        
        
    }
   
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:self.tableView]) {
        return [super tableView:self.tableView heightForRowAtIndexPath:indexPath];
    }else
        return 30;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:self.tableView]) {
        ManagerSearchedModel *model = [self.dataSource objectAtIndex:indexPath.row];
   
        
        [BCLoginViewController checkLoggedInWithBlock:^(BOOL isLoggedIn) {
            if (isLoggedIn) {
                BCManagerInfoViewController *info = [[BCManagerInfoViewController alloc]initWithUid:model.uid];
                [self.navigationController pushViewController:info animated:YES];

            }
        }];
        
    }else
    {
               if ([self.searchConditionArray isEqual:self.bankArray]) {
            self.bank = [[self.searchConditionArray objectAtIndex:indexPath.row]valueForKey:@"name"];
                   [self.bankBtn setTitle:self.bank forState:UIControlStateNormal];
        }else if([self.searchConditionArray isEqual:self.workArray])
        {
            self.work = [[self.searchConditionArray objectAtIndex:indexPath.row]valueForKey:@"name"];
            [self.workBtn setTitle:self.work forState:UIControlStateNormal];

        }
        else if([self.searchConditionArray isEqual:self.sortArray])
        {
            self.sort = [[self.searchConditionArray objectAtIndex:indexPath.row] objectAtIndex:1];
            [self.sortBtn setTitle:[[self.searchConditionArray objectAtIndex:indexPath.row] objectAtIndex:0] forState:UIControlStateNormal];
        }else{
            self.city = [[self.searchConditionArray objectAtIndex:indexPath.row] objectAtIndex:1];
             [self.cityBtn setTitle:[[self.searchConditionArray objectAtIndex:indexPath.row] objectAtIndex:0] forState:UIControlStateNormal];
        }
        
        __weak typeof(self)weakSel = self;
        [self hideSearchConditionCompeletion:^{
            [BCProgressHUD showWithTile:@"搜索中" animated:YES];
        [BCNetworkClient searchWithKey:weakSel.keyWord
        auth:USER_MANAGER.auth
        city:weakSel.city
        work:weakSel.work
        bank:weakSel.bank
        order:weakSel.sort
        desc:@"1"
        start:0
        limit:SearchLimit
        success:^(NSArray *results) {
            [BCProgressHUD hideAnimated:YES];
            weakSel.dataSource = [ManagerSearchedModel modelsWithDataSource:results];
            weakSel.nextStart = weakSel.dataSource.count;
            [weakSel.tableView reloadData];
        }
        failure:^(NSError *error) {
            [BCProgressHUD hideWithError:error animated:YES];
            
        }];

        }];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

}


#pragma mark Data Source Loading / Reloading Methods





- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
    {
        if ([scrollView isEqual:self.tableView]) {
            [self hideSearchConditionCompeletion:^{
                
            }];
        }
    }


- (void)dealloc
{
    [_header free];
    [_footer free];
}

#pragma mark condition transform

-(void)hideSearchConditionCompeletion:(void(^)())block
{
    __weak typeof(self)weakSelf = self;
   [UIView animateWithDuration:0.1 delay:0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
        weakSelf.conditionTableView.frame = CGRectSetHeight(weakSelf.conditionTableView.frame, 0);
   } completion:^(BOOL finished) {
       if (block) {
           block();
       }
   }];
    
}

-(void)showTheSearchConditionWithX:(CGFloat)x
                       Compeletion:(void(^)())block
{
    __weak typeof(self)weakSelf = self;
    __block CGFloat y;
    switch ((int)x) {
        case 205:
            y = 37;
            break;
            
        default:
            y = 79;
            break;
    }
    
    [self hideSearchConditionCompeletion:^{
        weakSelf.conditionTableView.frame = CGRectSetX(self.conditionTableView.frame, x);
        weakSelf.conditionTableView.frame = CGRectSetY(self.conditionTableView.frame, y);
        [weakSelf conditonTableSetDataSource:[[NSArray alloc]init]];
        [weakSelf.conditionTable reloadData];
    
        [UIView animateWithDuration:0.15 delay:0.1 options:UIViewAnimationOptionAllowUserInteraction animations:^{
        weakSelf.conditionTableView.frame = CGRectSetHeight(weakSelf.conditionTableView.frame,110);
        } completion:^(BOOL finished) {
            if (block) {
                block();
            }
        }];
        
        
    }];
    
}

-(void)conditonTableSetDataSource:(NSArray *)array
{
    self.searchConditionArray = array;
    [self.conditionTable reloadData];
}


- (IBAction)cityBtnPressed:(UIButton *)sender {
    __weak typeof(self)weakSelf = self;
    if (weakSelf.selected_tag != sender.tag) {
        [self showTheSearchConditionWithX:205
                              Compeletion:^{
                                  [weakSelf conditonTableSetDataSource:weakSelf.cityArray];
                                  
                              }];
    }else
    {
        [self hideSearchConditionCompeletion:^{
            weakSelf.selected_tag = 0;
        }];
    }
    self.selected_tag = sender.tag;
}


- (IBAction)bankConditionBtnPressed:(UIButton *)sender{
     __weak typeof(self)weakSelf = self;
    if (weakSelf.selected_tag != sender.tag) {
        [self showTheSearchConditionWithX:0
                              Compeletion:^{
                [weakSelf conditonTableSetDataSource:weakSelf.bankArray];

                              }];
    }else
    {
        [self hideSearchConditionCompeletion:^{
                        weakSelf.selected_tag = 0;
        }];
    }
      self.selected_tag = sender.tag;
}


- (IBAction)workBtnPressed:(UIButton *)sender {
    __weak typeof(self)weakSelf = self;

    if (weakSelf.selected_tag != sender.tag) {
        [self showTheSearchConditionWithX:107
                              Compeletion:^{
            [weakSelf conditonTableSetDataSource:weakSelf.workArray];
                              }];
    }else
    {
        [self hideSearchConditionCompeletion:^{
                        weakSelf.selected_tag = 0;
        }];
    }
    self.selected_tag = sender.tag;
    
}

- (IBAction)sortBtnPressed:(id)sender {
    __weak typeof(self)weakSelf = self;
    __weak UIButton *btn = (UIButton *)sender;
     if (weakSelf.selected_tag != btn.tag) {
         
    [self showTheSearchConditionWithX:213 Compeletion:^{
        [weakSelf conditonTableSetDataSource:weakSelf.sortArray];
    }];
     }
     else
     {
         [self hideSearchConditionCompeletion:^{
                     weakSelf.selected_tag = 0;
     }];
     }
    self.selected_tag = btn.tag;
}

@end
